import bcrypt from 'bcryptjs'
import { SignJWT, jwtVerify } from 'jose'
import { NextRequest } from 'next/server'

const JWT_SECRET = new TextEncoder().encode(process.env.NEXTAUTH_SECRET || 'your-secret-key')

export interface User {
  id: number
  email: string
  username: string
  role: string
}

export async function hashPassword(password: string): Promise<string> {
  return bcrypt.hash(password, 12)
}

export async function verifyPassword(password: string, hashedPassword: string): Promise<boolean> {
  return bcrypt.compare(password, hashedPassword)
}

export async function generateToken(user: User): Promise<string> {
  return await new SignJWT({
    id: user.id,
    email: user.email,
    username: user.username,
    role: user.role
  })
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('7d')
    .sign(JWT_SECRET)
}

export async function verifyToken(token: string): Promise<User | null> {
  try {
    console.log('[Auth] 验证token，长度:', token.length)
    console.log('[Auth] JWT_SECRET存在:', !!JWT_SECRET)
    const { payload } = await jwtVerify(token, JWT_SECRET)
    console.log('[Auth] Token验证成功，用户:', payload.username)
    return {
      id: payload.id as number,
      email: payload.email as string,
      username: payload.username as string,
      role: payload.role as string
    }
  } catch (error) {
    console.log('[Auth] Token验证失败:', error instanceof Error ? error.message : error)
    return null
  }
}

export function getTokenFromRequest(request: NextRequest): string | null {
  const authHeader = request.headers.get('authorization')
  if (authHeader && authHeader.startsWith('Bearer ')) {
    return authHeader.substring(7)
  }
  
  // 也可以从cookie中获取token
  const token = request.cookies.get('auth-token')?.value
  return token || null
}

export async function getUserFromRequest(request: NextRequest): Promise<User | null> {
  const token = getTokenFromRequest(request)
  if (!token) return null

  return await verifyToken(token)
}
